package cn.rengy.tool.excel;

import cn.rengy.util.ExceptionPrintUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class ExcelWriteBuilder {
    private final OutputStream outputStream;
    private SXSSFWorkbook workbook;

    private ExcelWriter excelWriter;
    public ExcelWriteBuilder(OutputStream outputStream){
        this.outputStream=outputStream;
        this.workbook = new SXSSFWorkbook();
        this.excelWriter=new ExcelWriter(workbook);
    }

    public ExcelWriterSheetBuilder sheet(String sheetName) {
        ExcelWriterSheetBuilder excelWriterSheetBuilder = new ExcelWriterSheetBuilder(excelWriter);
        excelWriterSheetBuilder.sheetName(sheetName);
        return excelWriterSheetBuilder;
    }

    public void finish() {
        try {
            workbook.write(outputStream);
        } catch (Exception e) {
            log.error(ExceptionPrintUtils.getTrace(e));
        }finally{
            try {
                workbook.close();
            } catch (IOException e) {
                log.error(ExceptionPrintUtils.getTrace(e));
            }

            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                log.error(ExceptionPrintUtils.getTrace(e));
            }
        }
    }
}
